package org.arain.baseii.connect;

import javax.servlet.http.HttpServletRequest;

import org.arain.baseii.system.user.SysUserDto;
import org.arain.baseii.utils.AppUtils;
import org.arain.baseii.utils.ArainResult;
import org.arain.baseii.utils.TimeUtil;
import org.arain.baseii.websocket.SystemWebSocketHandler;
import org.arain.baseii.websocket.talk.TaklHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;

@Controller
@RequestMapping("connect")
public class ConnectController {
	@Autowired
	private ConnectService connectService;
	@Bean  
    public TaklHandler talk() {  
        return new TaklHandler();  
    }  
	
	@Bean  
    public SystemWebSocketHandler systemWebSocketHandler() {  
        return new SystemWebSocketHandler();  
    }  
	
	
	@RequestMapping("add_01")
	public String add_01(Model model,String username) {
		model.addAttribute("username", username);
		return "connect/add_01";
	}
	
	@RequestMapping("talk.do")
	@ResponseBody
	public ArainResult talk_01(HttpServletRequest request,ConnectDto dto) {
		ArainResult result = connectService.save_01(dto);
		if (result.getStatus()==200) {
			talk().sendMessageToUser(dto.getReceiver(), new TextMessage(TimeUtil.getNow()+"："+dto.getMsg()));  
			systemWebSocketHandler().refresh(connectService,dto.getReceiver());
		}
		return ArainResult.ok();
	}
	
	@RequestMapping("read")
	@ResponseBody
	public ArainResult read(HttpServletRequest request,ConnectDto dto) {
		ArainResult result = connectService.load_talk(dto);
		if(result.getStatus()==200) {
			systemWebSocketHandler().refresh(connectService,AppUtils.getUserName());
		}
		return result;
	}
	
	@RequestMapping("search_user")
	@ResponseBody
	public ArainResult search_user(HttpServletRequest request,SysUserDto dto) {
		 return connectService.search_user(dto);
	}
}
